//
//  ViewController.swift
//  TestDemo
//
//  Created by isoftstone on 2018/9/17.
//  Copyright © 2018年 isoftstone. All rights reserved.
//

import UIKit
import CoreData
class ViewController: UIViewController {
    lazy var second:String = {
        return "second"
    }()
 
    lazy var managedObjectModel : NSManagedObjectModel = {
        guard let modelURL = Bundle.main.url(forResource: "TestData", withExtension: "momd") else {
            fatalError("failed to find data model")
        }
        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
            fatalError("Failed to create model from file: \(modelURL)")
        }
        return mom
    }()
    lazy var persistanceCoordinator : NSPersistentStoreCoordinator = {
        let psc = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
        let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
        let fileURL = URL(string: "db.sqlite", relativeTo: dirURL)
        
        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: fileURL, options: nil)
        } catch {
            fatalError("Error configuring persistent store: \(error)")
        }
        return psc
    }()
   
    lazy var managedObjectContext : NSManagedObjectContext = {
        let moc = NSManagedObjectContext(concurrencyType:.mainQueueConcurrencyType)
        moc.persistentStoreCoordinator = persistanceCoordinator
        return moc
    }()



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        let people = NSEntityDescription.insertNewObject(forEntityName: "Person", into: managedObjectContext) as! Person
        people.name = "test1"
        do {
             try managedObjectContext.save()
            print("保存成功")
        }catch let error{
            print("context can't save!, Error:\(error)")
        }
        
    
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        //        let predicate = NSPredicate(format:"id=1")  //设置查询条件按照id查找不设置查询条件，则默认全部查找
        
        //        fetchRequest.predicate=predicate
        do {
            
            let peopleList =
                
                try managedObjectContext.fetch(fetchRequest)as! [NSManagedObject]
            
            print("打印查询结果")
            
            for person in peopleList as! [Person] {
                
                print("查询到的人是\(person.name!)")
                
                //修改操作:将查询到的结果修改后，再调用context.save()保存即可
                
                if (person.name == "do"){
                    
                    person.name="do"
                    
                }
                if (person.name == "finish"){
                    
                    managedObjectContext.delete(people)
                
                    
                }
                //删除操作:将查询到的额结果删除后，再调用context.save()保存即可
                if(person.name == "test1"){
                    person.name = "小红"
                }
               
                
               
                
            }
            
        } catch let error{
            
            print("context can't fetch!, Error:\(error)")
            
        }
        
        do {
            try managedObjectContext.save()
        }catch let error{
            print("context can't change!, Error:\(error)")
        }
    
    }

}

